package com.leonzx.base.controller.api;

import com.google.gson.Gson;
import com.leonzx.base.config.security.Digests;
import com.leonzx.base.constants.IMConstants;
import com.leonzx.base.controller.base.BaseController;
import com.leonzx.base.entity.system.User;
import com.leonzx.base.service.RedisService;
import com.leonzx.base.service.system.OrdersService;
import com.leonzx.base.service.system.UserService;
import com.leonzx.base.utils.Constants;
import com.leonzx.base.utils.RedisConstants;
import com.leonzx.base.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author:李晓雷
 * @Description:
 * @Date: 18/07/09 14:43
 */
@Api("移动app相关接口")
@RestController
@RequestMapping("/api/app")
public class ApiController extends BaseController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    /**
     * 静态模版所在路径前缀
     */
    private String prefix = "layim";

    /**
     * @param username
     * @param password
     * @return
     */

    @ApiOperation(value = "app登录接口", notes = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password) {
        Map<String, Object> result = new HashMap<>();

        User user = userService.getByUsername(username);
        if (user == null) {
            result.put("code", "401");
            result.put("msg", "用户登陆失败");
            return gson.toJson(result);
        } else {
            String jmmm = Digests.md5(password, username, Digests.HASH_INTERATIONS);
            if (!jmmm.equals(user.getPassword())) {
                result.put("code", "401");
                result.put("msg", "用户登陆失败");
                return gson.toJson(result);
            }
        }
        //生成token 数据 缓存token
        String token = UUIDUtils.getUUID();
        redisService.setKey(RedisConstants.USER_TOKEN + token, gson.toJson(user));
        result.put("token", token);
        result.put("data", user);
        result.put("code", "200");
        result.put("msg", "用户登陆成功");
        return gson.toJson(result);
    }

    /**
     * 上传图片接口
     *
     * @param number
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public String uploadImg(String number, MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = getMap();
        Gson gson = new Gson();
        try {
            result = ordersService.uploadImg(number, file, request);
            result.put("code", '1');
            logger.error("上传图片成功 " + number + "");
        } catch (Exception e) {
            logger.error("上传图片失败 " + number + "", e);
            result.put("code", '0');
        }
        return gson.toJson(result);
    }

    /**
     * @param number
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
    public String uploadVideo(String number, MultipartFile file) {
        Map<String, Object> result = getMap();
        Gson gson = new Gson();
        try {
            result = ordersService.uploadVideo(number, file);
            result.put("code", "0");
        } catch (Exception e) {
            logger.error("上传视频失败", e);
            result.put("code", '0');
        }
        return gson.toJson(result);
    }

    @RequestMapping(value = "/getImg", method = RequestMethod.GET)
    public void getImg(String key, HttpServletResponse resp) throws IOException {
        ordersService.getInputStream(key, resp);
    }

    @RequestMapping(value = "/login/online", method = RequestMethod.POST)
    public Map<String, Object> online(String userId) {
        Map<String, Object> result = new HashMap<>();
        try {

            User user = userService.getUserById(userId);
            if (!Objects.equals(IMConstants.IM_STATUS_HIDE, user.getImStatus())) {
                user.setImStatus(IMConstants.IM_STATUS_ONLINE);
                userService.update(user);
            }
            redisService.setKey(RedisConstants.JIM_USER_STATUS + userId, Constants.STATE_VAILD + "");
        } catch (Exception e) {
            logger.error("上线错误", e);
        }
        return result;
    }

    @RequestMapping(value = "/login/offline", method = RequestMethod.POST)
    public Map<String, Object> offline(String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.getUserById(userId);
            if (!Objects.equals(IMConstants.IM_STATUS_HIDE, user.getImStatus())) {
                user.setImStatus(IMConstants.IM_STATUS_OFFLINE);
                userService.update(user);
            }
            redisService.remove(RedisConstants.JIM_USER_STATUS + userId);
        } catch (Exception e) {
            logger.error("下线错误", e);
        }
        return result;
    }
}
